package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.common.R;
import com.reggie.common.ValidateCodeUtils;
import com.reggie.dto.orderDto;
import com.reggie.entity.*;
import com.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Transactional
@RestController
@RequestMapping("/order")
public class ordersController {
    @Autowired
    private ordersService ordersService;

    @Autowired
    private shoppingCartService shoppingCartService;

    @Autowired
    private addressBookService addressBookService;

    @Autowired
    private userService userService;

    @Autowired
    private orderDetailService orderDetailService;
    private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return com.reggie.common.R<com.baomidou.mybatisplus.extension.plugins.pagination.Page>
     * @description: 订单的查询功能
     * @author 86187
     * @date: 2022/11/20 19:57
     */

    @GetMapping("/page")
    public R<Page> selectOrdersByCondition(int page, int pageSize, Long number, String beginTime, String endTime) {
        LocalDateTime begin = null;
        LocalDateTime end = null;
        String numberTemp = null;
        //将string日期转换成LocalDateTime类型
        if (beginTime != null) {
            begin = LocalDateTime.parse(beginTime, dateTimeFormatter);
        }
        if (endTime != null) {
            end = LocalDateTime.parse(endTime, dateTimeFormatter);
        }
        //将Long类型的number转换成String
        if (number != null) {
            numberTemp = String.valueOf(number);
        }
        //设置Page
        Page<orders> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(number != null, orders::getNumber, numberTemp);
        queryWrapper.gt(begin != null, orders::getOrderTime, begin);
        queryWrapper.lt(end != null, orders::getOrderTime, end);
        ordersService.page(pageInfo, queryWrapper);
        log.info("进行了订单的查询");
        return R.success(pageInfo);
    }

    /**
     * @param orders
     * @param session
     * @return com.reggie.common.R<java.lang.String>
     * @description: 保存提交的订单
     * @author 86187
     * @date: 2022/11/26 11:46
     */

    @PostMapping("/submit")
    public R<String> submitOrder(@RequestBody orders orders, HttpSession session) {
        LambdaQueryWrapper<shoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<user> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //获取用户名
        Long userId = (Long) session.getAttribute("user");
        shoppingCartLambdaQueryWrapper.eq(userId != null, shoppingCart::getUserId, userId);
        //查询对应购物车的商品
        List<shoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
        //再处理订单
        addressBookLambdaQueryWrapper.eq(orders.getAddressBookId() != null, AddressBook::getId, orders.getAddressBookId());
        //获取地址簿
        AddressBook addressBook = addressBookService.getOne(addressBookLambdaQueryWrapper);
        //获取当前账号的用户名
        userLambdaQueryWrapper.eq(userId != null, user::getId, userId);
        user user = userService.getOne(userLambdaQueryWrapper);
        //给orders填充地址内容和用户名等
        orders.setAddress(addressBook.getDetail());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);
        orders.setUserName(user.getName());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(BigDecimal.valueOf(0));
        //生成八位数的订单号
        orders.setNumber(ValidateCodeUtils.generateValidateCode(8));
        //遍历购物车，将商品的价格进行计算,订单完成后，就将购物车清空，该用户的
        shoppingCartList.forEach(t -> {
            orders.setAmount(orders.getAmount().add(t.getAmount()));
        });
        //先提交订单生成id
        boolean save = ordersService.save(orders);
        //重新拿到获得id的order
        //创建List接收
        List<OrderDetail> detailList = new ArrayList<>();
        //foreach购物车
        shoppingCartList.forEach(t -> {
            OrderDetail detail = new OrderDetail();
            //复制购物车商品的属性到detail
            BeanUtils.copyProperties(t, detail, "id", "createTime");
            //给与此次的订单id
            detail.setOrderId(orders.getId());
            detailList.add(detail);
        });
        //最后将detailList保存到order_detail表中
        boolean saveBatch = orderDetailService.saveBatch(detailList);
        //保存成功后，将购物车清空
        boolean remove = shoppingCartService.remove(shoppingCartLambdaQueryWrapper);
        if (saveBatch && save) {
            return R.success("下单成功!");
        }
        //执行插入操作
        log.info("成功保存订单:{}", orders.getId());
        return R.error("结算失败!请稍后再试!");
    }

    /**
     * @param orders
     * @return com.reggie.common.R<java.lang.String>
     * @description: 修改订单的状态
     * @author 86187
     * @date: 2022/11/26 12:46
     */

    @PutMapping()
    public R<String> alterOrderStatus(@RequestBody orders orders) {
        boolean b = ordersService.updateById(orders);
        if (b) {
            return R.success("修改成功!");
        }
        return R.error("修改失败!");
    }

    /**
     * @param page
     * @param pageSize
     * @param session
     * @return com.reggie.common.R<com.baomidou.mybatisplus.extension.plugins.pagination.Page>
     * @description: 订单查询
     * @author 86187
     * @date: 2022/11/26 13:00
     */

    @GetMapping("/userPage")
    public R<Page<orderDto>> orderList(int page, int pageSize, HttpSession session) {
        Long userId = (Long) session.getAttribute("user");
        Page<orders> pageInfo = new Page<>(page, pageSize);
        Page<orderDto> dtoPage = new Page<>();
        LambdaQueryWrapper<orders> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(userId != null, orders::getUserId, userId);
        ordersService.page(pageInfo, queryWrapper);
        //属性复制
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        //创建list
        List<orderDto> orderDtoList = new ArrayList<>();
        //遍历
        pageInfo.getRecords().forEach(t -> {
            orderDto dto = new orderDto();
            BeanUtils.copyProperties(t, dto);
            List<OrderDetail> list = orderDetailService.list(orderDetailLambdaQueryWrapper.eq(t.getId() != null, OrderDetail::getOrderId, t.getId()));
            dto.setOrderDetails(list);
            orderDtoList.add(dto);
        });
        dtoPage.setRecords(orderDtoList);
        log.info("查看历史订单:{}", userId);
        return R.success(dtoPage);
    }
}
